﻿@implements IDisposable
@inject PersistentComponentState ApplicationState
@inject IDemoDataModel           Data
@inject ILogger<Weather>         Logger

<PageTitle>Weather</PageTitle>

<h1>Weather</h1>

<p>Page parameters</p>

<table class="table w-auto">
	<thead>
		<tr>
			<th>Parameter</th>
			<th>Value</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td>Operating System</td>
			<td>@(OperatingSystem.IsBrowser() ? "Browser" : "Server")</td>
		</tr>
		<tr>
			<td>RendererInfo</td>
			<td>@RendererInfo.Name</td>
		</tr>
		<tr>
			<td>IsInteractive</td>
			<td>@(RendererInfo.IsInteractive ? "Yes" : "No")</td>
		</tr>
		<tr>
			<td>DataModel Type</td>
			<td>@(Data.GetType())</td>
		</tr>
	</tbody>
</table>

<p>This component demonstrates showing data.</p>

@if (_forecasts == null)
{
	<p><em>Loading...</em></p>
}
else
{
	<table class="table">
		<thead>
			<tr>
				<th>Date</th>
				<th aria-label="Temperature in Celsius">Temp. (C)</th>
				<th aria-label="Temperature in Farenheit">Temp. (F)</th>
				<th>Summary</th>
			</tr>
		</thead>
		<tbody>
			@foreach (var forecast in _forecasts)
			{
				<tr>
					<td>@forecast.Date.ToShortDateString()</td>
					<td>@forecast.TemperatureC</td>
					<td>@forecast.TemperatureF</td>
					<td>@forecast.Summary</td>
				</tr>
			}
		</tbody>
	</table>
}

@code {
	WeatherForecast[]?                    _forecasts;
	PersistingComponentStateSubscription? _persistingSubscription;

	protected override void OnInitialized()
	{
		// In some rendering modes Blazor renders content twice.
		// This is a workaround to minimize the visible effect.
		//
		_persistingSubscription = ApplicationState.RegisterOnPersisting(() =>
		{
			Logger.LogInformation("Persisting state");

			if (_forecasts is not null)
				ApplicationState.PersistAsJson("forecasts", _forecasts);
			return Task.CompletedTask;
		});

		if (ApplicationState.TryTakeFromJson("forecasts", out _forecasts))
			Logger.LogInformation("Restored state");
	}

	protected override async Task OnInitializedAsync()
	{
		_forecasts ??= await Data.Model.WeatherForecasts.ToArrayAsync();
	}

	public void Dispose()
	{
		_persistingSubscription?.Dispose();
	}
}
